// src/components/NodePanel.jsx
import { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave } from '@fortawesome/free-solid-svg-icons';

export default function NodePanel({ node, onSave, onClose }) {

  const [agentConfig, setAgentConfig] = useState({
    ...(node.data.config || {})
  });

  console.log('agentConfig: ', agentConfig)
  console.log('node: ', node)

  useEffect(() => {
    setAgentConfig({
      ...(node.data.config || {})
    });
  }, [node.data]); 

  // if (node.type === 'inputNode') return null;

  const handleConfigChange = (newConfig) => {
    setAgentConfig(prev => ({ ...prev, ...newConfig }));
  }

  const handleSubmit = () => {
    onSave(node.id, agentConfig);
    onClose();
  };

  // 设置工具参数
  const handleParamChange = (index, field, value) => {
    const newParams = [...agentConfig.params];
    newParams[index][field] = value;
    
    // 自动设置默认值示例
    if (field === 'type') {
      switch (value) {
        case 'number':
          newParams[index].defaultValue = '0';
          break;
        case 'boolean':
          newParams[index].defaultValue = 'true';
          break;
        case 'json':
          newParams[index].defaultValue = '{}';
          break;
        default:
          newParams[index].defaultValue = '';
      }
    }
    setAgentConfig(prev => ({ ...prev, params: newParams }));
  };

  // 添加工具参数
  const handleAddParam = () => {
    setAgentConfig(prev => ({
      ...prev,
      params: [...prev.params, { name: '', description: '', type: 'string' }]
    }));
  };

  const parseValue = (value) =>  {
    try {
      // 尝试解析为 JSON
      return typeof value === 'object' ? JSON.stringify(value, null, 2) : value.toString();
    } catch {
      // 如果解析失败，返回原始值
      return value;
    }
  }

  // 接口测试函数
  const handleHttpTest = async () => {
    const method = agentConfig.method.toUpperCase();
    try {
      if (!agentConfig.url) {
        alert('请输入访问地址 URL');
        return;
      }
      // 转换headers为对象格式
      const headersObj = agentConfig.headers.reduce((acc, { key, value }) => {
        if (key) acc[key] = value;
        return acc;
      }, {});
      // 处理请求体
      let body;
      if (!['GET', 'HEAD'].includes(agentConfig.method.toUpperCase())) {
        body = agentConfig.input_data;
        // 自动处理JSON格式
        const contentType = headersObj['Content-Type']?.toLowerCase();
        if (contentType === 'application/json' && agentConfig.input_data) {
          try {
            body = JSON.stringify(JSON.parse(agentConfig.input_data));
          } catch (error) {
            console.error('JSON解析失败，使用原始数据');
          }
        }
      }
      // 发送请求
      const response = await fetch(agentConfig.url, {
        method,
        headers: headersObj,
        body: ['GET', 'HEAD'].includes(agentConfig.method.toUpperCase()) ? undefined : body
      });
      console.log('响应状态：', response.status);
      // 处理响应
      const contentType = response.headers.get('content-type');
      let result;
      if (contentType?.includes('application/json')) {
        result = JSON.stringify(await response.json(), null, 2);
      } else {
        result = await response.text();
        console.log('响应结果：', result);
      }

      handleConfigChange({ content: result });
    } catch (error) {
      handleConfigChange({ content: `请求失败：${error.message}` });
    }
  };
  
  return (
    <div className="w-[600px] bg-white border-l border-gray-200 h-full flex flex-col">
      <div className="p-6 border-b">
        <div className="flex justify-between items-center mb-6">
          {node.type === 'agentConfig' ? '智能体配置' : '节点配置'}
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 text-2xl"
          >
            &times;
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-6 pr-4">
        {
          (node.data.agent_type === '输入型'   || node.type === 'inputNode') && (
            <div className="space-y-5">
              <div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {node.type === 'agentConfig' ? '智能体名称' : '节点名称'}
                  </label>
                  <input
                    value={agentConfig.label || ''}
                    onChange={(e) => handleConfigChange({ label: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">输出格式</label>
                  <select
                    value={agentConfig.inputType}
                    onChange={(e) => handleConfigChange({ inputType: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    <option value="string">字符串文本</option>
                    <option value="number">数字</option>
                    <option value="boolean">布尔值</option>
                    <option value="json">JSON</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    描述
                  </label>
                  <textarea
                    value={agentConfig.desc || ''}
                    onChange={(e) => handleConfigChange({ desc: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg h-20 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    内容
                  </label>
                  <textarea
                    value={parseValue(agentConfig.content) || ''}
                    onChange={(e) => handleConfigChange({ content: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg h-80 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

              </div>
            </div>
          )
        }

        {
          (node.data.agent_type === '输出型'  || node.type === 'outputNode') && (
            <div className="space-y-5">
              <div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {node.type === 'agentConfig' ? '智能体名称' : '节点名称'}
                  </label>
                  <input
                    value={agentConfig.label || ''}
                    onChange={(e) => handleConfigChange({ label: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    描述
                  </label>
                  <textarea
                    value={agentConfig.desc || ''}
                    onChange={(e) => handleConfigChange({ desc: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg h-20 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">是否展示输出端点</label>
                  <select
                    value={agentConfig.out_handle}
                    onChange={(e) => handleConfigChange({ out_handle: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    <option value="yes">是</option>
                    <option value="no">否</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    json 解析（例如：key1.key2[0].key3）
                  </label>
                  <input
                    placeholder='为空表示输出完整数据'
                    value={agentConfig.selectedVariable || ''}
                    onChange={(e) => handleConfigChange({ selectedVariable: e.target.value })}
                    className="w-full px-3 py-1 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 mb-1"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    内容
                  </label>
                  <textarea
                    value={parseValue(agentConfig.content) || ''}
                    onChange={(e) => handleConfigChange({ content: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg h-80 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

              </div>
            </div>
          )
        }

        {
          (node.data.agent_type === '对话型' || node.type === 'agentNode') && (

            <div className="space-y-5">
              <div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {node.type === 'agentConfig' ? '智能体名称' : '节点名称'}
                  </label>
                  <input
                    value={agentConfig.label || ''}
                    onChange={(e) => handleConfigChange({ label: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    模型名称
                  </label>
                  <input
                    value={agentConfig.modelName || ''}
                    onChange={(e) => handleConfigChange({ modelName: e.target.value })}
                    className="w-full px-3 py-1 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 mb-1"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    API 地址
                  </label>
                  <input
                    value={agentConfig.apiUrl || ''}
                    onChange={(e) => handleConfigChange({ apiUrl: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    API Key
                  </label>
                  <input
                    value={agentConfig.apiKey || ''}
                    onChange={(e) => handleConfigChange({ apiKey: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                      最大 Token 数
                    </label>
                    <input
                      type="number"
                      value={agentConfig.maxPrompt || 0}
                      onChange={(e) => handleConfigChange({ maxPrompt: e.target.value })}
                      className="w-full px-3 py-2 border rounded-lg"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    Temperature ({agentConfig.temperature || 0})
                  </label>
                  <input
                    type="range"
                    min="0"
                    max="2"
                    step="0.1"
                    value={agentConfig.temperature || 0.7}
                    onChange={(e) => handleConfigChange({ temperature: e.target.value })}
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    系统提示
                  </label>
                  <textarea
                    value={agentConfig.desc || ''}
                    onChange={(e) => handleConfigChange({ desc: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg h-32 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>
            </div>
          )
        }

        {
          (node.data.agent_type === '工具型' || node.type === 'toolNode') && agentConfig.params && (
            <div className="space-y-5">
              <div>
                <div>
                  <label>节点名称</label>
                  <input
                    value={agentConfig.label}
                    onChange={(e) => handleConfigChange({ label: e.target.value })}
                    className="w-full border p-2 rounded"
                    pattern="[A-Za-z0-9_]+"
                    required
                  />
                </div>
                <div>
                  <label>工具名称</label>
                  <input
                    value={agentConfig.toolName}
                    onChange={(e) => handleConfigChange({ toolName: e.target.value })}
                    className="w-full border p-2 rounded"
                    pattern="[A-Za-z0-9_]+"
                    required
                  />
                  {!/^[A-Za-z0-9_]+$/.test(agentConfig.toolName) && (
                    <p className="text-red-500 text-sm">工具名称只能包含英文、数字或下划线！</p>
                  )}
                </div>

                <div>
                  <label>工具描述</label>
                  <textarea
                    value={agentConfig.desc}
                    onChange={(e) => handleConfigChange({ desc: e.target.value })}
                    className="w-full border p-2 rounded h-20"
                  />
                </div>

                <div>
                  <label>执行类型</label>
                  <select
                    value={agentConfig.execType}
                    onChange={(e) =>  handleConfigChange({ execType: e.target.value })}
                    className="w-full border p-2 rounded"
                  >
                    <option value="HTTP 请求">HTTP 请求</option>
                    <option value="Python 代码">Python 代码</option>
                  </select>
                </div>
                
                <div className="mt-1 mb-1">
                  <label>参数列表</label>
                  {agentConfig.params.map((param, index) => (
                    <div>
                      <div key={index} className="flex gap-2">
                        <input
                          placeholder="参数名称"
                          value={param.name}
                          onChange={(e) => handleParamChange(index, 'name', e.target.value)}
                          className="w-28 border p-1 rounded"
                          pattern="[A-Za-z0-9_]+"
                        />
                        <select
                          value={param.type || 'string'}
                          onChange={(e) => handleParamChange(index, 'type', e.target.value)}
                          className="w-24 border p-1 rounded bg-white"
                        >
                          <option value="string">字符串</option>
                          <option value="number">数字</option>
                          <option value="boolean">布尔值</option>
                          <option value="json">JSON</option>
                        </select>
                        <input
                          placeholder="参数描述"
                          value={param.description}
                          onChange={(e) => handleParamChange(index, 'description', e.target.value)}
                          className="flex-1 border p-1 rounded"
                        />
                        <button
                          onClick={() => {
                              const newParams = agentConfig.params.filter((_, i) => i !== index);
                              setAgentConfig({ ...agentConfig, params: newParams });
                          }}
                          className="px-2 text-red-500 hover:text-red-700"
                          title="删除参数"
                          >
                          ×
                        </button>
                      </div>
                      {!/^[A-Za-z0-9_]+$/.test(param.name) && (
                        <p className="text-red-500 text-sm">参数名称只能包含英文、数字或下划线！</p>
                      )}
                    </div>
                  ))}
                  <button onClick={handleAddParam} className="text-blue-500 text-sm">
                    + 添加参数
                  </button>
                </div>

                {agentConfig.execType === 'Python 代码' ? (
                  <div>
                    <label>Python 代码</label>
                    <textarea
                      value={agentConfig.codeContent}
                      onChange={(e) => setAgentConfig({ ...agentConfig, codeContent: e.target.value })}
                      className="w-full border p-2 rounded h-32 font-mono text-sm"
                    />
                  </div>
                ) : (
                  <div className="mt-1 mb-1">
                    <div>
                      <label>请求URL</label>
                      <input
                        value={agentConfig.httpConfig.url}
                        onChange={(e) => setAgentConfig({
                          ...agentConfig,
                          httpConfig: { ...agentConfig.httpConfig, url: e.target.value }
                        })}
                        className="w-full border p-2 rounded"
                        type="url"
                      />
                    </div>
                    
                    <div>
                      <label>请求方式</label>
                      <select
                        value={agentConfig.httpConfig.method}
                        onChange={(e) => setAgentConfig({
                          ...agentConfig,
                          httpConfig: { ...agentConfig.httpConfig, method: e.target.value }
                        })}
                        className="w-full border p-2 rounded"
                      >
                        {['GET', 'POST', 'PUT', 'DELETE'].map(method => (
                          <option key={method} value={method}>{method}</option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <h3 className="font-medium">请求头</h3>
                      {agentConfig.httpConfig.headers.map((header, index) => (
                        <div key={index} className="flex gap-2 mb-2">
                          <input
                            placeholder="Header Key"
                            value={header.hkey}
                            onChange={(e) => {
                              const newHeaders = [...agentConfig.httpConfig.headers];
                              newHeaders[index].hkey = e.target.value;
                              setAgentConfig({
                                ...agentConfig,
                                httpConfig: { ...agentConfig.httpConfig, headers: newHeaders }
                              });
                            }}
                            className="flex-1 border p-1 rounded"
                          />
                          <input
                            placeholder="Header Value"
                            value={header.hvalue}
                            onChange={(e) => {
                              const newHeaders = [...agentConfig.httpConfig.headers];
                              newHeaders[index].hvalue = e.target.value;
                              setAgentConfig({
                                ...agentConfig,
                                httpConfig: { ...agentConfig.httpConfig, headers: newHeaders }
                              });
                            }}
                            className="flex-1 border p-1 rounded"
                          />
                          <button
                            onClick={() => {
                              const newHeaders = agentConfig.httpConfig.headers.filter((_, i) => i !== index);
                              setAgentConfig({
                                ...agentConfig,
                                httpConfig: { ...agentConfig.httpConfig, headers: newHeaders }
                              });
                            }}
                            className="px-2 text-red-500 hover:text-red-700"
                            title="删除Header"
                          >
                            ×
                          </button>
                        </div>
                      ))}
                      <button 
                        onClick={() => setAgentConfig({
                          ...agentConfig,
                          httpConfig: { 
                            ...agentConfig.httpConfig, 
                            headers: [...agentConfig.httpConfig.headers, { key: '', value: '' }]
                          }
                        })} 
                        className="text-blue-500 text-sm"
                      >
                        + 添加Header
                      </button>
                    </div>
                  </div>
                )}



              </div>
            </div>
          )
        }

        {
          (node.data.agent_type === '网络型' || node.type === 'httpNode') && (

            <div className="space-y-5">
              <div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {node.type === 'agentConfig' ? '智能体名称' : '节点名称'}
                  </label>
                  <input
                    value={agentConfig.label || ''}
                    onChange={(e) => handleConfigChange({ label: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">访问地址 URL</label>
                  <input
                    value={agentConfig.url}
                    onChange={(e) => handleConfigChange({url: e.target.value})}
                    className="w-full px-3 py-1 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">请求方法</label>
                  <select
                    value={agentConfig.method}
                    onChange={(e) => handleConfigChange({method: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    {['GET', 'POST', 'PUT', 'DELETE'].map(method => (
                      <option key={method} value={method}>{method}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <h3 className="font-medium">请求头</h3>
                  {agentConfig.headers.map((header, index) => (
                    <div key={index} className="flex gap-2 mb-2">
                      <input
                        placeholder="Header Key"
                        value={header.key}
                        onChange={(e) => {
                          const newHeaders = [...agentConfig.headers];
                          newHeaders[index].key = e.target.value;
                          handleConfigChange({headers: newHeaders});
                        }}
                        className="flex-1 border p-1 rounded"
                      />
                      <input
                        placeholder="Header Value"
                        value={header.value}
                        onChange={(e) => {
                          const newHeaders = [...agentConfig.headers];
                          newHeaders[index].value = e.target.value;
                          handleConfigChange({headers: newHeaders});
                        }}
                        className="flex-1 border p-1 rounded"
                      />
                      <button
                        onClick={() => {
                          const newHeaders = agentConfig.headers.filter((_, i) => i !== index);
                          handleConfigChange({headers: newHeaders});
                        }}
                        className="px-2 text-red-500 hover:text-red-700"
                        title="删除Header"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                  <button 
                    onClick={() => setAgentConfig({
                      ...agentConfig,
                      headers: [...agentConfig.headers, { key: '', value: '' }]
                    })} 
                    className="text-blue-500 text-sm"
                  >
                    + 添加Header
                  </button>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    请求数据
                  </label>
                  <textarea
                    value={agentConfig.input_data}
                    onChange={(e) => handleConfigChange({input_data: e.target.value})}
                    className="w-full px-3 py-2 h-32 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div className="mt-4">
                  <button
                    onClick={handleHttpTest}
                    className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg transition-colors"
                  >
                    测试接口
                  </button>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1 mt-2">
                    请求结果
                  </label>
                  <textarea
                    value={agentConfig.content}
                    onChange={(e) => handleConfigChange({content: e.target.value})}
                    className="w-full px-3 py-2 h-32 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

              </div>
            </div>
          )
        }

        {/* {
          node.data.type === '输入型' && (
            <div className="space-y-5">
              <div>

              </div>
            </div>
          )
        } */}

        
      
      
      </div>

      <div className="p-6 pt-0">
        <button
          className="w-full bg-blue-500 hover:bg-blue-600 text-white py-2 rounded-lg transition-colors"
          onClick={handleSubmit}
        >
          <FontAwesomeIcon icon={faSave} className="mr-2" />
          保存配置
        </button>
      </div>
    </div>
  );
}